//
//  HomeSubController.m
//  JKScanTool
//
//  Created by jike on 16/5/23.
//  Copyright © 2016年 YM. All rights reserved.
//

#import "HomeSubController.h"
#import "HomeProductCell.h"
#import "ZBarScanVC.h"
@interface HomeSubController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;//数据源
    UIView *_backEditView;
    UIView *_editView;
    NSString *_proID;
    FeWifiManHub *_loading; //菊花
    
    NSString * _urlIndex;//起始页
    NSString *_totalCount;//总页数
    BOOL _isLoading; //正在刷新的时候不让加载数据，否则会崩溃
    NSIndexPath *_indexPath;//刷新指定行..
    UIView * _backTView;
    
}
@property(nonatomic,strong)UITextField *codeTf;
@end

@implementation HomeSubController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[AppData share].scanSuccess2Refresh isEqualToString:@"isScanSuccess"]) {
        if (_indexPath.row < _dataArray.count) {
            [_dataArray removeObjectAtIndex:_indexPath.row];
            [_tableView reloadData];
        }
        [AppData share].scanSuccess2Refresh = @"";
    }
    [self registerForKeyboardNotifications];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _urlIndex = @"1";
    _isLoading = NO;
    _dataArray = [[NSMutableArray alloc]init];
    _proID = @"";
    _loading = [[FeWifiManHub alloc] initWithView:[UIApplication sharedApplication].keyWindow withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 64, _loading.frame.size.width, _loading.frame.size.height);
    [[UIApplication sharedApplication].keyWindow addSubview:_loading];
    [_loading show];
    
    [self SetUpMainTableView];//创建tableview
    [self setUpEditView];
    [self loadData];//加载数据
    [self setUpBackViewWithImage:@"noOrder" tips:@"暂无相关产品"];
}
- (void)SetUpMainTableView {
    self.view.backgroundColor = BackColor;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 - 35) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = 80;
    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    _tableView.footer = footer;
    
    [self.view addSubview:_tableView];
    
}
#pragma mark -- 下拉刷新
- (void)refreshData {
    if (_isLoading) {
        return;
    }
    _urlIndex = @"1";
    _isLoading = YES;
    [self loadData];
}
#pragma mark -- 上啦加载
- (void)loadMore {
    if (_isLoading) {
        if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
            [_tableView.footer noticeNoMoreData];
            [_tableView.footer endRefreshing];
        }
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
        [_tableView.footer noticeNoMoreData];
        [_tableView.footer endRefreshing];
        return;
    }
    _urlIndex  = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
    [self loadData];
}
- (void)loadData {
    
    if (![Utils isConnectionAvailable]) {
        [_loading dismiss];
    }
    NSArray * TypeArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"TType"];
    NSString *cid;
    if (_currentPage - 1 < TypeArr.count) {
        cid = TypeArr[_currentPage - 1];
        NSLog(@"%@",cid);
    }
    NSString * kurl;
    if (_currentPage == 0) {
        kurl = [NSString stringWithFormat:ScanAllList,@"15",_urlIndex,[Utils md5SignStr],_MainID];
    }else {
        //#define ScanList BaseUrl @"/WPT-OpenAPI?control=ShopCommon&action=SearchProdByPrdName&pagesize=%@&pageIndex=%@&sign=%@&categoryid=%@"
        kurl = [NSString stringWithFormat:ScanList,@"15",_urlIndex,[Utils md5SignStr],cid];
    }
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    
    [AFNetworkHandler GETWithAFNByURL:kurl completion:^(id result) {
        NSDictionary * dic = result;
        NSLog(@"0000000000000066666--%@---%@",kurl,result);
        
        if ([dic[@"r"] isEqualToString:@"T"]) {
            NSArray *arr = [dic objectForKey:@"d"];
            _totalCount = [dic objectForKey:@"totalPage"];
            
            [_dataArray addObjectsFromArray:arr];
        }
        if ([_totalCount isEqualToString:@"0"] || _totalCount.length == 0) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        _isLoading = NO;
        
        [_loading dismiss];
        [_tableView reloadData];
    }];
    
    
}

- (void)setUpBackViewWithImage:(NSString *)image tips:(NSString *)tip {
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [_tableView addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:image];//@"noSearch"
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = tip;//@"抱歉，没有找到相关订单"
    [_backTView addSubview:label];
}
#pragma mark -- 编辑视图
- (void)setUpEditView {
    _backEditView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    _backEditView.backgroundColor = SetColor(0, 0, 0, 0.3);
    _backEditView.hidden = YES;
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endEdit)];
    [_backEditView addGestureRecognizer:tapG];
    [[UIApplication sharedApplication].keyWindow addSubview:_backEditView];
    //编辑视图
    _editView = [[UIView alloc]initWithFrame:CGRectMake(15, (ScreenHeight - 132)/2, ScreenWidth - 30, 132)];
    _editView.backgroundColor = [UIColor whiteColor];
    [_backEditView addSubview:_editView];
    _editView.layer.cornerRadius = 5;
    _editView.layer.masksToBounds = YES;
    
    for (int i = 0;i < 2; i++) {
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 44 * i, ScreenWidth - 20, 44)];
        textField.borderStyle = UITextBorderStyleNone;
        textField.font = [UIFont systemFontOfSize:13];
        textField.tag = 1000 + i;//100,101,
        if (i == 1) {
            textField.placeholder = @"请输入13位有效的条形码";
            textField.keyboardType = UIKeyboardTypeDecimalPad;
            textField.delegate = self;
        }else {
            textField.enabled = NO;
        }
        [_editView addSubview:textField];
        
        //lineView
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,44 + 44 * i, _editView.frame.size.width,0.5)];
        lineView.backgroundColor = SetColor(0, 0, 0, 0.2);
        [_editView addSubview:lineView];
    }
    //保存按钮
    NSArray *titleArr = @[@"取消",@"保存"];
    for (int i = 0; i < 2; i++) {
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.frame = CGRectMake(15 + (_editView.frame.size.width - 30)/2 *i, 88, (_editView.frame.size.width - 30)/2, 44);
        [sureBtn setTitle:titleArr[i] forState:UIControlStateNormal];
        sureBtn.tag = 120 + i;
        [sureBtn setTitleColor:MainColor forState:UIControlStateNormal];
        [_editView addSubview:sureBtn];
        [sureBtn addTarget:self action:@selector(sureBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}
#pragma mark -- 保存
-(void)sureBtnClicked:(UIButton *)sender
{
    if (sender.tag == 120) {//取消
        [self endEdit];
    }else if (sender.tag == 121){
        UITextField *titleT = (UITextField *)[_backEditView viewWithTag:1001];
        NSString *str = titleT.text;
        if (str.length == 13) {
            if (![Utils isConnectionAvailable]) { //断网
                [[MessShowView share] showWithMess:@"断网了啦"];
            }else{
                [self sendCode:str];
            }
        }else{
            [[MessShowView share] showWithMess:@"请输入正确的条形码"];
        }
    }
}
#pragma mark ---上传条码
-(void)sendCode:(NSString *)str
{
    _loading = [[FeWifiManHub alloc] initWithView:[UIApplication sharedApplication].keyWindow withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 64, _loading.frame.size.width, _loading.frame.size.height);
    [[UIApplication sharedApplication].keyWindow addSubview:_loading];
    [_loading show];
    
    NSString *kUrl;
    kUrl = [NSString stringWithFormat:UpLoadInformation,[AppData share].realLoginName,str,_proID];
    [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
        NSDictionary *dic = result;
        NSString *result1 = [dic objectForKey:@"m"];
        if ([result1 isEqualToString:@"success"]) {
            [_loading dismiss];
            [[MessShowView share] showWithMess:@"上传成功啦"];
            [UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self endEdit];
            } completion:nil];
            if (_indexPath.row < _dataArray.count) {
                [_dataArray removeObjectAtIndex:_indexPath.row];
                [_tableView reloadData];
            }
        }else{
            [_loading dismiss];
            [[MessShowView share] showWithMess:@"上传失败"];
        }
    }];
}
- (void)endEdit {
    _editView = [[UIView alloc]initWithFrame:CGRectMake(15, (ScreenHeight - 132)/2, ScreenWidth - 30, 132)];
    _backEditView.hidden = YES;
    [_backEditView endEditing:YES];
    [_editView endEditing:YES];
}
#pragma mark -- 移除通知
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];//移除全部通知。
}
#pragma mark -- 添加监听
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
#pragma mark -- 键盘高度
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    CGRect inputFieldRect = _editView.frame;
    NSLog(@"==%f",inputFieldRect.origin.y + 132 - ( ScreenHeight + yOffset));
    NSLog(@"y:%f",yOffset);
    if (inputFieldRect.origin.y + 132 > ScreenHeight + yOffset) {//遮挡..
        CGFloat offset= (inputFieldRect.origin.y + 132 - (ScreenHeight + yOffset));
        inputFieldRect.origin.y -= offset;
        [UIView animateWithDuration:duration animations:^{
            _editView.frame = inputFieldRect;
        }];
    }
}
#pragma mark --tableview DELEGATE..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0001;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"homecell";
    HomeProductCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"HomeProductCell" owner:nil options:nil] firstObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.scanBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
    [cell.editBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
    if (indexPath.row < [_dataArray count]) {
        [cell.iconImageView sd_setImageWithURL:[_dataArray[indexPath.row] objectForKey:@"img"] placeholderImage:[UIImage imageNamed:@"fanglanmao"]];
        cell.titleLabel.text = [_dataArray[indexPath.row] objectForKey:@"name"];
        NSDictionary *dic = [[_dataArray[indexPath.row] objectForKey:@"properties"] firstObject];
        cell.descLabel.text = [dic objectForKey:@"propertyname"];
        cell.priceLabel.text = [dic objectForKey:@"saleprice"];
    }
    return cell;
}
- (void)BtnClick:(UIButton *)sender WithEvent:(id)event {
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_tableView];
    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
    _indexPath = indexPath;
    UITextField *titleT = (UITextField *)[_backEditView viewWithTag:1000];
    UITextField *numT = (UITextField *)[_backEditView viewWithTag:1001];
    if (indexPath!= nil)
    {
        if (sender.tag == 10) {
            ZBarScanVC *scanVC = [[ZBarScanVC alloc]init];
            scanVC.productId = [_dataArray[indexPath.row] objectForKey:@"id"];
            if (_myBlock) {
                _myBlock(scanVC);
            }
            NSLog(@"23");
        }else if (sender.tag == 11){
            if (indexPath.row < _dataArray.count) {
                titleT.text = [_dataArray[indexPath.row] objectForKey:@"name"];
                _proID = [_dataArray[indexPath.row] objectForKey:@"id"];
            }
            numT.text = @"";
            numT.placeholder = @"请输入13位有效的条形码";
            _backEditView.hidden = NO;
        }
    }
}
#pragma mark ---UITextField代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 1001) {//条码
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        if (toBeString.length > 13) {
            
            return NO;
            
        }else{
            
            //  判断输入的是否为数字 (只能输入数字)
            NSString *validRegEx =@"^[0-9]*$";
            NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", validRegEx];
            BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:string];
            if (myStringMatchesRegEx){
                return YES;
            }else{
                return NO;
            }
        }
        
       
    }else{
        
        return NO;
    }
}


@end
